// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
use std::fs;
use std::env;
use std::io::Write;
use std::fs::OpenOptions;

#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn app_run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_serialplugin::init())
        .invoke_handler(tauri::generate_handler![greet,read_cfg_data,write_gps_data])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

#[tauri::command]
fn read_cfg_data()->String{
    let args: Vec<String> = env::args().collect();
    let base_path = &args[0];
    
    let cfg_path = base_path.replace("app2.exe", "config.txt");
    let contents = fs::read_to_string(cfg_path)
        .expect("读取失败~~!");
    //println!("{contents}");
    
    contents
}

#[tauri::command]
fn write_gps_data(ss: &str) ->Result<i32,i32>{
    let args: Vec<String> = env::args().collect();
    let base_path = &args[0];
    
    let gps_path = base_path.replace("app2.exe", "GPS数据.txt");
    let mut file = OpenOptions::new().append(true).open(gps_path).expect("打开文件 failed");

    file.write_all(ss.as_bytes()).expect("Write file fail~!");
    file.write_all("\r\n".as_bytes()).expect("Rust write file err~!");

    Ok(0)
}